package com.vv.ossupload.handler;

import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.file.Files;

/**
 * @author kw
 * @program upload-demo
 * @description
 * @create 2025 - 06 - 21 11:32
 **/
@Component
public class AwsOssUploadHandler {

    @Autowired
    private AmazonS3 amazonS3;

    public void putObject(String bucketName, String key, File file) {
        amazonS3.putObject(bucketName, key, file);
    }

    public void putObject(String bucketName, String key, MultipartFile file) {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        // 设置⾃定义元数据
        objectMetadata.addUserMetadata("k1", URLEncoder.encode("v1"));
        // 使⽤该接⼝时，必须使⽤ 设置请求体⼤⼩不然，sdk会把数据囤在内存⾥计算⼀遍⼤⼩先，在上传，容易造成oom
        objectMetadata.setContentLength(file.getSize());
        try {
            PutObjectResult result = amazonS3.putObject(bucketName, key, file.getInputStream(), objectMetadata);
            System.out.println(" 上传成功，etag:" + result.getETag());
        } catch (AmazonServiceException e) {
            // TODO上传报错，发⽣在通信过程
        } catch (SdkClientException e) {
            // TODO上传报错，此时请求还未发出，客⼾端原因

        } catch (IOException e) {
            // TODO ⽂件流异常处理

        }
    }
}
